package com.example.qcrmdemo.Controller;

import com.example.qcrmdemo.entity.CstManager;
import com.example.qcrmdemo.entity.Customer;
import com.example.qcrmdemo.service.CstManagerService;
import com.example.qcrmdemo.service.CustomerService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class CustomerController {
    private static final Logger logger= LoggerFactory.getLogger(CustomerController.class);
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CstManagerService cstManagerService;
    /**
     * 返回客户信息页面
     * @return
     */
    @GetMapping("/KeHuGuanLi/customer")
    public ModelAndView CustomerView(
            @RequestParam(name="pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize",required = true,defaultValue = "5") int pageSize,
            @RequestParam(name = "keyword",required = false) String keyword
    ){
        ModelAndView mav=new ModelAndView("KeHuGuanLi/customer");
        //调用服务方法查询分页的客户数据
        PageInfo<Customer> page= customerService.selectAll();
//        System.out.println(page);
        mav.addObject("page",page);
//        mav.addObject("keyword",keyword);
        return mav;
    }

    /**
     * 返回客户信息添加页面
     * @return
     */
    @GetMapping("/KeHuGuanLi/customer_add")
    public ModelAndView CustomerAddView(){
        ModelAndView mav=new ModelAndView("KeHuGuanLi/customer_add");
        List<CstManager> productType=cstManagerService.selectAll();
        mav.addObject("productType",productType);
        return mav;
    }

    /**
     * 新增用户
     * @param customer
     * @param bindingResult
     * @return
     */
    @PostMapping("/KeHuGuanLi/customer_add")
    //Validated注解所标注的参数，表面该参数中的属性取值必须要按照属性上定义的验证规则进行验证，验证是由验证框架完成的
    //验证的结果会以BindingResult实例的形式传入到该方法
    public ModelAndView customerAdd(@Validated Customer customer, BindingResult bindingResult){
        //redirect表示重定向响应
        //给浏览器仅仅只发送一个请求地址，而没有任何视图内容或者数据
        //浏览器会使用收到的地址，重新发送一个get请求，由于是新请求，因此没有缓存上一次请求的数据，从而达到防止重复提交表单的请求
        ModelAndView mav=new ModelAndView("redirect:/KeHuGuanLi/customer_add");
        Map<String,String > errorMessage =new HashMap<>();
        if(bindingResult.hasErrors()){
            //如果有验证错误信息，那么要进行处理
            //获得出现错误域，以及相应的错误消息文本
            final List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            //错误放到映射中
            for (FieldError error:fieldErrors){
                //从每一个域错误对象中取出域名称，错误消息，加到映射中
                errorMessage.put(error.getField(),error.getDefaultMessage());
            }
            //将错误保存到视图
            mav.addObject("errorMessage",errorMessage);
            mav.addObject("customer",customer);
            //由于没有保存数据，因此不必进行重定向，内部转发请求到视图。同时，还要以保留请求数据，以及响应的信息
            mav.setViewName("KeHuGuanLi/customer_add");
        }else{
            //如果没有有验证错误信息，验证通过，保存客户信息
            //调用服务方法保存客户数据
            boolean result= customerService.append(customer);
            if(result){
                logger.info("新增客户信息成功 - " + customer);
            }else {
                logger.info("新增客户信息失败 - " + customer);
            }
        }
        return mav;
    }
//    @GetMapping("/KeHuGuanLi/customer_view")
//    public ModelAndView CustomerDetialView(){
//        ModelAndView mav=new ModelAndView("KeHuGuanLi/customer_view");
//        return mav;
//    }
//    @GetMapping("/KeHuGuanLi/customer_modify")
//    public  ModelAndView customerModifyView(
//            @RequestParam(name = "id",required = true) int id,
//            @RequestParam(name = "pageSize",required = true,defaultValue = "5") int pageSize,
//            @RequestParam(name="pageNum",required = true,defaultValue = "1") int pageNum,
//            @RequestParam(name = "keyword",required = false) String keyword
//
//    ){
//        ModelAndView mav=new ModelAndView("/KeHuGuanLi/customer_modify");
//        //调用服务方法根据ID查询要编辑的客户
//        Customer customer =customerService.findById(id);
//        mav.addObject("customer",customer);
//        return mav;
//    }
//    @PostMapping("/customer/customer_modify")
//    public ModelAndView customerModify(
//            Customer customer,
//            @RequestParam(name="pageNum",required = true,defaultValue = "1") int pageNum,
//            @RequestParam(name = "pageSize",required = true,defaultValue = "5") int pageSize,
//            @RequestParam(name = "keyword",required = false) String keyword
//
//    ) throws UnsupportedEncodingException {
//        String redirectUrl = "redirect:/KeHuGuanLi/customer_list?pageNum="+pageNum+
//                "&pageSize="+pageSize +
//                "&keyword="+ URLEncoder.encode(keyword,"utf-8");
//
//        ModelAndView mav=new ModelAndView("KeHuGuanLi/customer_modify");
//        boolean result=customerService.modify(customer);
//        return mav;
//    }

}
